package com.fot.config;

import com.fot.core.RedisMQTemplate;
import com.fot.core.publisher.RedisMQMessagePublisher;
import lombok.NonNull;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration(
        proxyBeanMethods = false
)
@EnableConfigurationProperties({RedisMQProperties.class})
@Import({ListenerContainerConfiguration.class, RedisMQListenerConfiguration.class})
@AutoConfigureBefore(RedissonClient.class)
public class RedisMqAutoConfiguration implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    public static final String PUBLISHER_BEAN_NAME = "redisMQPublisher";

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean(PUBLISHER_BEAN_NAME)
    @ConditionalOnMissingBean(RedisMQMessagePublisher.class)
    public RedisMQMessagePublisher redisMQMessagePublisher(RedissonClient redissonClient) {
        return new RedisMQMessagePublisher(redissonClient);
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisMQTemplate redisMQTemplate() {
        RedisMQTemplate redisMQTemplate = new RedisMQTemplate();
        redisMQTemplate.setRedisMQMessagePublisher((RedisMQMessagePublisher) applicationContext.getBean(PUBLISHER_BEAN_NAME));
        return redisMQTemplate;
    }
}
